﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProductionResourceAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class UpdateProductionResourceCommand : ProductionResourceEditRequestDto,
        IRequest<Result<ProductionResourceInfoResponseDto>>
    {
        public int Id { get; set; }
    }

    public class UpdateProductionResourceCommandHandler : IRequestHandler<UpdateProductionResourceCommand,
        Result<ProductionResourceInfoResponseDto>>
    {
        private readonly IProductionResourceRepository _productionResourceRepository;
        private readonly IMapper _mapper;

        public UpdateProductionResourceCommandHandler(IProductionResourceRepository productionResourceRepository,
            IMapper mapper)
        {
            _productionResourceRepository = productionResourceRepository;
            _mapper = mapper;
        }

        public async Task<Result<ProductionResourceInfoResponseDto>> Handle(UpdateProductionResourceCommand request,
            CancellationToken cancellationToken)
        {
            var productionResource = await _productionResourceRepository.Get(request.Id);
            if (productionResource != null)
            {
                productionResource.Update(request.Code, request.Name, request.IsResourceGroup, request.IsStopGroup,
                    request.ResourceCategory, request.MaxLoad, request.PipelineInterval, request.IdleTime,
                    request.Quantity, request.Sort, request.Description);
            }

            await _productionResourceRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<ProductionResourceInfoResponseDto>.SuccessAsync(
                _mapper.Map<ProductionResourceInfoResponseDto>(productionResource));
        }
    }
}